package com.example.demo.common.config;

import com.example.demo.common.constant.CodeConst;
import com.example.demo.common.dto.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author kangds
 * 全局的的异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 全局异常.
     *
     * @param e the e
     * @return R
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R<?> exception(Exception e) {
        log.error("全局异常信息 ex={}", e.getMessage());
        return R.build().failed(e.getCause());
    }

    /**
     * validation Exception
     *
     * @param exception 异常
     * @return R
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    @ResponseStatus(HttpStatus.OK)
    public R<?> bodyValidExceptionHandler(MethodArgumentNotValidException exception) {
        List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
        return R.build().failed().failed(CodeConst.PARARM_ERROR, fieldErrors.get(0).getDefaultMessage());
    }

    @ExceptionHandler(Throwable.class)
    public R<?> handleAllThrowable(Throwable throwable) {
        return R.build().failed(throwable);
    }

}
